package com.dkm.modules.sys.operator.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dkm.commons.Response;
import com.dkm.constant.Constant;
import com.dkm.exception.ServiceException;
import com.dkm.modules.sys.operator.mapper.UserDataScopeMapper;
import com.dkm.modules.sys.operator.model.*;
import com.dkm.modules.sys.operator.service.OperatorService;
import com.dkm.modules.sys.role.model.RolePO;
import com.dkm.modules.sys.role.service.RoleService;
import com.dkm.modules.sys.user.mapper.UserMapper;
import com.dkm.modules.sys.user.model.AddUser;
import com.dkm.modules.sys.user.model.EditUser;
import com.dkm.modules.sys.user.model.User;
import com.dkm.modules.sys.user.service.UserService;
import com.dkm.modules.wx.cashrecord.mapper.OperatorBalanceMapper;
import com.dkm.modules.wx.cashrecord.model.OperatorBalance;
import com.dkm.modules.wx.rule.mapper.CustomPriceMapper;
import com.dkm.modules.wx.rule.mapper.RuleMapper;
import com.dkm.modules.wx.rule.model.CustomPrice;
import com.dkm.modules.wx.rule.model.Rule;
import com.dkm.modules.wx.rule.service.CustomPriceService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @ClassName OperatorServiceImpl
 * @Description: 运营端-代理商操作
 * @Author 杨膑
 * @Date 2019/9/4
 * @Version V1.0
 **/
@Service
public class OperatorServiceImpl implements OperatorService {

    @Autowired
    private UserService userService;
    @Autowired
    private OperatorBalanceMapper operatorBalanceMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RuleMapper ruleMapper;
    @Autowired
    private CustomPriceService customPriceService;
    @Autowired
    private CustomPriceMapper customPriceMapper;
    @Autowired
    private UserDataScopeMapper userDataScopeMapper;
    @Autowired
    private RoleService roleService;


    /**
     * @描述 添加代理商
     * @参数 [operator 代理商信息]
     * @返回值 com.dkm.commons.Response
     * @创建人 yangbin
     * @创建时间 2019/10/1
     */
    @Override
    @Transactional
    public Response addUser(AddUser operator) {

        operator.setIsOperator(Constant.USER_IS_OPERATOR);
        try {
            userService.addUser(operator);
        } catch (Exception e) {
            return Response.error(-1, e.getMessage());
        }
        int id = userMapper.selectById(operator.getUseraccount()).getId();
        // 插入代理商余额表
        OperatorBalance validOperatorBalance = operatorBalanceMapper.selectById(id);
        if (validOperatorBalance == null) {
            OperatorBalance operatorBalance = new OperatorBalance();
            operatorBalance.setUserId(id);
            operatorBalance.setVersion(1);
            operatorBalance.setAmount(0.0f);
            operatorBalance.setCreateTime(new Date());
            /*插入代理商余额表*/
            operatorBalanceMapper.insert(operatorBalance);
        }

        /*获取平台默认卡规则*/
        QueryWrapper<Rule> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_sys_give", 1);
        List<Rule> sysRule = ruleMapper.selectList(queryWrapper);
        for (Rule rule : sysRule) {
            Integer sysRuleId = rule.getId();
            // 查询平台规则中价格
            List<CustomPrice> customPrices = customPriceService.getCustomPriceByRuleId(sysRuleId);
            rule.setUserId(id);
            rule.setIsGive(1);
            rule.setChangeName(operator.getRealName() + "默认");
            rule.setIsSysGive(0);
            rule.setId(null);
            rule.setCreatetime(new Date());
            /*插入代理商默认规则*/
            ruleMapper.insert(rule);
            //插入价格规则
            if (customPrices.size() > 0) {
                // 循环插入价格
                for (CustomPrice price : customPrices) {
                    price.setId(null);
                    price.setCreatetime(new Date());
                    price.setRuleId(rule.getId());
                    customPriceMapper.insert(price);
                }
            }
        }
        return Response.ok(0, "添加成功");
    }

    @Override
    /**
     *@描述 分页查询代理商列表
     *@参数 [page, params]
     *@返回值 com.baomidou.mybatisplus.core.metadata.IPage<com.dkm.modules.sys.operator.model.OperatorResult>
     *@创建人 yangbin
     *@创建时间 2019/10/1
     */
    public IPage<OperatorResult> getOperatorList(Page<OperatorResult> page, Map<String, String> params) {
        List<OperatorResult> list = userMapper.getOperatorList(page, params);
        // 设置角色信息
        setRoleArr(list);
        page.setRecords(list);
        return page;
    }

    private void setRoleArr(List<OperatorResult> list) {
        if(CollectionUtils.isEmpty(list)){
            return;
        }
        for (OperatorResult operatorResult : list) {
            // 获取
            List<RolePO> roles = roleService.getRoleByUserId(operatorResult.getId());
            if(CollectionUtils.isEmpty(roles)){
                operatorResult.setRoleArr("");
                continue;
            }
            String arr = roles.stream().map(RolePO::getRoleName).collect(Collectors.joining(","));
            operatorResult.setRoleArr(arr);
        }
    }

    @Override
    /**
     *@描述 删除代理商
     *@参数 [id 代理商ID]
     *@返回值 void
     *@创建人 yangbin
     *@创建时间 2019/10/19
     */
    public void delOperator(Integer id) {
        EditUser editUser = new EditUser();
        editUser.setId(id);
        editUser.setState(Constant.XT_USER_DELETE);
        userService.updateUserByNm(editUser);
    }

    @Override
    /**
     *@描述 修改代理商
     *@参数 [user]
     *@返回值 void
     *@创建人 yangbin
     *@创建时间 2019/10/20
     */
    public void editOperator(EditUser user) {
        userService.updateUser(user);
    }

    @Override
    /**
     *@描述 获取代理商select
     *@参数 []
     *@返回值 java.util.List<com.dkm.modules.sys.operator.model.OperatorSelect>
     *@创建人 yangbin
     *@创建时间 2019/10/27
     */
    public List<OperatorSelect> getOperatorSelect() {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_operator", 1);
        queryWrapper.ne("state", 2);
        List<User> users = userMapper.selectList(queryWrapper);
        List<OperatorSelect> operatorSelects = new ArrayList<>();
        for (User user : users) {
            OperatorSelect o = new OperatorSelect();
            o.setOperatorNm(user.getRealName());
            o.setOperatorId(user.getId());
            operatorSelects.add(o);
        }
        return operatorSelects;
    }

    @Override
    public void setOperatorsForUser(SetOperatorDTO setOperatorDTO) {
        Integer userId = setOperatorDTO.getUserId();
        User user = userMapper.selectByUserId(userId);
        if (Objects.isNull(user)) {
            throw new ServiceException("运营者不存在");
        }
        Map<String, Object> hashMap = new HashMap<>();
        hashMap.put("user_id", userId);
        userDataScopeMapper.deleteByMap(hashMap);

        List<Integer> operatorIds = setOperatorDTO.getOperatorIds();
        for (Integer operatorId : operatorIds) {
            UserDatascopePO userDatascopePO = new UserDatascopePO(userId, operatorId);
            userDataScopeMapper.insert(userDatascopePO);
        }
    }

    @Override
    public List<User> getAllUser() {

        QueryWrapper<User> eq = new QueryWrapper<User>().eq("is_operator", 0).eq("state", 1);

        return userMapper.selectList(eq);
    }

    @Override
    public IPage<UserOperator> getUserOperatorsByPage(String keyWord, Page<UserOperator> p) {
        List<UserOperator> users = userMapper.selectByPage(keyWord, p);
        p.setRecords(users);
        return p;
    }

    @Override
    public void deleteOpertaors(Integer id) {
        userDataScopeMapper.deleteById(id);
    }


    @Override
    public Response getAccumulatedAmount(int operatorId) {
        BigDecimal accumulatedAmount = userMapper.getAccumulatedAmount(operatorId);
        if(null==accumulatedAmount){
            accumulatedAmount = BigDecimal.ZERO;
        }
        accumulatedAmount = accumulatedAmount.setScale(2, RoundingMode.HALF_DOWN);
        return Response.ok(accumulatedAmount);
    }

    @Override
    public Response setUpRoyaltyPercent(int operatorId, BigDecimal royaltyPercent) {
        Integer num = userMapper.setUpRoyaltyPercent(operatorId,royaltyPercent);
        if(num > 0){
            return Response.ok();
        }else{
            return Response.error(Constant.SUCCESS_CODE,-10,"设置分成失败！",null);
        }
    }

}
